﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace WSDZ.KM.ZH.RepairOrderArchive
{
    [Description("维修工单归档生成记录单"), HotUpdate]
    public class RepairOrderArchive : AbstractOperationServicePlugIn
    {
        public string logType { get; set; } = "维修工单归档生成记录单";
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            //List<int> IdList = e.SelectedRows.Select(x => x.DataEntity["Id"].ToInt32V1()).Distinct().Where(y => y != 0).ToList();
            List<int> IdList = e.DataEntitys.Select(x => x["Id"].ToStringV1().ToInt32V1()).Distinct().Where(y => y != 0).ToList();
            if (IdList == null || IdList.Count < 1)
                return;
            Main(IdList);
        }
        public void Main(List<int> IdList)
        {
            List<RepairData> dataList = new List<RepairData>();
            int size = 2000;
            int icount = IdList.Count <= size ? 1 : IdList.Count % size > 0 ? IdList.Count / size + 1 : IdList.Count / size;
            for (int i = 0; i < icount; i++)
            {
                List<int> ids = IdList.Skip(i * size).Take(size).ToList();
                if (ids.Count<1)
                    continue;
                string sql = $@"/*dialect*/ select 
Id=main.FID
,entyId=enty.FEntryID
,billNo=main.FBILLNO
,orgNumber=org.FNUMBER
,matNumber=mat.FNUMBER
,cplbNumber=cplb.FNUMBER
,wxryNumber=wxry.FNUMBER --维修人员
,custNumber=cust.FNUMBER --客户
from RLKX_t_RepairBill main
left join RLKX_t_Cust_WXGDCPMX enty on main.FID=enty.FID
left join T_ORG_ORGANIZATIONS org on main.F_RLKX_ORGID=org.FORGID
left join T_BD_MATERIAL mat on enty.F_RLKX_COBM=mat.FMATERIALID
left join T_BAS_PREBDTHREE cplb on enty.F_RLKX_CPLB=cplb.FID
--left join T_BAS_ASSISTANTDATAENTRY wxyy on enty
left join T_HR_EMPINFO wxry on enty.F_RLKX_SHRY=wxry.FID
left join T_BD_CUSTOMER cust on main.F_RLKX_CUSTOMER=cust.FCUSTID
where main.FID in ({string.Join(",", ids)})";
                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context,sql);
                List<RepairData> rlist = datas.DynamicObjectCollectionToDataList<RepairData>();
                if (rlist!=null)
                    dataList.AddRange(rlist);

            }
            if (dataList==null||dataList.Count<1)
                return;
            dataList = dataList.GroupBy(x => x.billNo).Select(y => y.OrderBy(a => a.entyId).FirstOrDefault()).ToList();
            K3HelperV1.Login(Context);
            foreach (var data in dataList)
            {
                try
                {
                    JObject Root = new JObject();
                    //Root["IsAutoSubmitAndAudit"] = true;
                    JObject Model = new JObject();
                    Model["FBillNo"] = data.billNo;
                    //业务组织
                    JObject F_RLKX_OrgId = new JObject();
                    F_RLKX_OrgId["FNumber"] = data.orgNumber;
                    Model["F_RLKX_OrgId"] = F_RLKX_OrgId;
                    //产品编码
                    JObject F_RLKX_cpbm = new JObject();
                    F_RLKX_cpbm["FNumber"] = data.matNumber;
                    Model["F_RLKX_cpbm"] = F_RLKX_cpbm;
                    //产品类别
                    JObject F_RLKX_cplb = new JObject();
                    F_RLKX_cplb["FNumber"] = data.cplbNumber;
                    Model["F_RLKX_cplb"] = F_RLKX_cplb;
                    //售后人员
                    JObject F_RLKX_shry = new JObject();
                    F_RLKX_shry["FSTAFFNUMBER"] = data.wxryNumber;
                    Model["F_RLKX_shry"] = F_RLKX_shry;
                    //客户
                    JObject F_RLKX_customer = new JObject();
                    F_RLKX_customer["FNumber"] = data.custNumber;
                    Model["F_RLKX_customer"] = F_RLKX_customer;

                    Root["Model"] = Model;
                    string json = Root.ToStringV1();
                    string msg = string.Empty;
                    bool isOk = K3HelperV1.Save(Context, "RLKX_RepairBIllRecord",json,ref msg);
                    if (isOk)
                        InitMessage(true, data.Id.ToStringV1(), data.billNo, "归档完成");
                    else
                        InitMessage(false, data.Id.ToStringV1(), data.billNo, $@"归档失败,{msg}");
                }
                catch (Exception ex)
                {
                    InitMessage(false, data.Id.ToStringV1(), data.billNo, $@"归档异常,{ex.Message}");
                    continue;
                }
            }
        }
        public void InitMessage(bool status, string id, string no, string msg)
        {
            this.OperationResult.IsShowMessage = true;
            OperateResult operate = new OperateResult()
            {
                SuccessStatus = true,
                PKValue = id,
                Number = no,
                Message = msg,
            };
            this.OperationResult.OperateResult.Add(operate);
        }

    }
    public class RepairData
    {
        public int Id { get; set; }
        public int entyId { get; set; }
        public string billNo { get; set; }
        public string orgNumber { get; set; }
        public string matNumber { get; set; }
        public string cplbNumber { get; set; }
        public string wxryNumber { get; set; }
        public string custNumber { get; set; }

    }
 
}
